﻿using DataSyncCom;
using DataSyncCommon;
using Newtonsoft.Json;
using Quartz;
using SupDataSync.Model;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace ConsoleSub
{
    /// <summary>
    /// 1.调用接口查询云端基础数据
    /// 2.将数据转换插入更新到本地
    /// 3.todo 将执行结果写入日志
    /// </summary>
    public class DownData : IJob
    {
        public DownData()
        {

        }
        public Task Execute(IJobExecutionContext context)
        {
            down();
            log($"执行下载任务结束{DateTime.Now}");
            return SysConfig.CompletedTask;
        }
        private void log(string str)
        {
            Console.WriteLine(str);
            LogHelper.CreateLoger().Error(str);
        }
        /// <summary>
        /// 查询基础数据addtype !=2的数据
        /// </summary>
        /// <returns></returns>
        public SyncResultModel GetData()
        {
            var url = SysConfig.url;
            var responseStr = HttpHelper.WebRequestApi(url + "/GetBaseData", JsonConvert.SerializeObject(SysConfig.TenantId), "POST");
            var syncResultList = JsonConvert.DeserializeObject<SyncResultModel>(responseStr);
            log($"{url + "/GetBaseData"}获取基础数据进行下载{syncResultList.vSyncBaseModel.CustomerList.Count}");
            return syncResultList;
        }

        public void down()
        {
            log(" 开始下载数据 "); 
            var datas = GetData();
            var str = InsertData(datas);
            var zxlog = LogHelper.InDbLog(new DataSyncCommon.Model.ba_sup_log()
            {
                NOTE = str,
                SYS_CODE = "down",
                TenantId = SysConfig.TenantId
            });
            log($"执行完成下载基础数据{zxlog}");
        }
        /// <summary>
        /// 根据id判断 如果有，修改 没有 插入
        /// </summary>
        /// <param name="model"></param>
        private string InsertData(SyncResultModel model)
        {
            var loger = LogHelper.CreateLoger();
            var log = "插入基础数据";
            using (var db = DbHelperMySql.GetSqlSugarDb())
            {
                loger.Error($"db{db.Context.Ado.Connection.ConnectionString}");
                try
                {
                    //测试南京金陵账号18711022000企业id 1061

                    var localmats = db.Queryable<ba_material>().Select(x => x.SYS_ID_KEY).ToList();
                    var ba_suppliers = db.Queryable<ba_supplier>().Select(x => x.SYS_ID_KEY).ToList();
                    var localcustomers = db.Queryable<ba_customer>().Select(x => x.customercode).ToList();
                    var localmattypes = db.Queryable<ba_material_type>().Select(x => x.SYS_ID_KEY).ToList();
                    var localunits = db.Queryable<ba_unit>().Select(x => x.SYS_ID_KEY).ToList();
                    var localflags = db.Queryable<ba_bar_flag>().Select(x => x.SYS_ID_KEY).ToList();
                    var localunitchs = db.Queryable<ba_mat_unit_chg>().Select(x => x.SYS_ID_KEY).ToList();
                    var localbarversions = db.Queryable<ba_bar_version>().Select(x => x.ID).ToList();
                    var localbarrules = db.Queryable<ba_bar_ruledetail>().Select(x => x.ID).ToList();
                    var localbadefines = db.Queryable<ba_name_define>().Select(x => x.ID).ToList();
                    log += ";ba_material：";
                    var i = 0;
                    db.BeginTran();
                    #region 数据处理
                    foreach (var item in model.vSyncBaseModel.MatList)
                    {
                        if (localmats.Contains(item.SYS_ID_KEY))
                        {
                            i += db.Updateable(item).ExecuteCommand();
                        }
                        else
                        {
                            i += db.Insertable(item).ExecuteCommand();
                        }
                    }
                    log += i + "，MatTypeList：";
                    i = 0;
                    foreach (var item in model.vSyncBaseModel.MatTypeList)
                    {
                        if (localmattypes.Contains(item.SYS_ID_KEY))
                        {
                            i += db.Updateable(item).ExecuteCommand();
                        }
                        else
                        {
                            i += db.Insertable(item).ExecuteCommand();
                        }
                    }
                    log += i + "，SupplierList：";
                    i = 0;
                    foreach (var item in model.vSyncBaseModel.SupplierList)
                    {
                        if (ba_suppliers.Contains(item.SYS_ID_KEY))
                        {
                            i += db.Updateable(item).ExecuteCommand();
                        }
                        else
                        {
                            i += db.Insertable(item).ExecuteCommand();
                        }
                    }
                    log += i + "，CustomerList：";
                    i = 0;
                    foreach (var item in model.vSyncBaseModel.CustomerList)
                    {
                        if (!localcustomers.Contains(item.customercode))
                        {
                            i += db.Insertable(item).ExecuteCommand();
                            //i += db.Updateable(item).ExecuteCommand();
                        }
                        else
                        {
                           
                        }
                    }
                    log += i + "，UnitList：";
                    i = 0;
                    foreach (var item in model.vSyncBaseModel.UnitList)
                    {
                        if (localunits.Contains(item.SYS_ID_KEY))
                        {
                            i += db.Updateable(item).ExecuteCommand();
                        }
                        else
                        {
                            i += db.Insertable(item).ExecuteCommand();
                        }
                    }
                    log += i + "，BarFlagList：";
                    i = 0;
                    foreach (var item in model.vSyncBaseModel.BarFlagList)
                    { 
                        if (localflags.Contains(item.SYS_ID_KEY))
                        {
                            i += db.Updateable(item).ExecuteCommand();
                        }
                        else
                        {
                            i += db.Insertable(item).ExecuteCommand();
                        }
                    }
                    log += i + "，MatUntiChgList：";
                    i = 0;
                    foreach (var item in model.vSyncBaseModel.MatUntiChgList)
                    {
                        if (localunitchs.Contains(item.SYS_ID_KEY))
                        {
                            i += db.Updateable(item).ExecuteCommand();
                        }
                        else
                        {
                            i += db.Insertable(item).ExecuteCommand();
                        }
                    }
                    log += i + "，BarVersionList：";
                    i = 0;
                    foreach (var item in model.vSyncBaseModel.BarVersionList)
                    {
                        if (localbarversions.Contains(item.ID))
                        {
                            i += db.Updateable(item).ExecuteCommand();
                        }
                        else
                        {
                            i += db.Insertable(item).ExecuteCommand();
                        }
                    }
                    log += i + "，BarRuleDetail：";
                    i = 0;
                    foreach (var item in model.vSyncBaseModel.BarRuleDetail)
                    {
                        if (localbarrules.Contains(item.ID))
                        {
                            i += db.Updateable(item).ExecuteCommand();
                        }
                        else
                        {
                            i += db.Insertable(item).ExecuteCommand();
                        }
                    }
                    log += i + "，BarRuleDetail：";
                    i = 0;
                    foreach (var item in model.vSyncBaseModel.NameDefineList)
                    {
                        if (localbadefines.Contains(item.ID))
                        {
                            i += db.Updateable(item).ExecuteCommand();
                        }
                        else
                        {
                            i += db.Insertable(item).ExecuteCommand();
                        }
                    }
                    log += i + "。。。";
                    #endregion
                    db.CommitTran();
                    loger.Error(log);
                    return log;
                }
                catch (Exception ex)
                {
                    db.RollbackTran();
                    loger.Error("插入数据失败" + ex.Message + log);
                    return ex.Message;
                }
            }
        }
    }
}
